package com.cyf.plc.data.local

import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import com.cyf.plc.data.local.dao.PlcDao
import com.cyf.plc.model.*

@Database(
    entities = [PlcFloor::class, PlcRoom::class, PlcAttribute::class, PlcSubAttribute::class, PlcFault::class],
    version = 1
)
abstract class PlcDatabase : RoomDatabase() {

    abstract fun getFloorDao(): PlcDao

    companion object {
        private const val DB_NAME = "plc_database.db"

        //        运行结果并不依赖变量的当前值，或者能够确保只有单一的线程修改变量的值。
//        变量不需要与其他的状态变量共同参与不变约束。
        @Volatile
        private var INSTANCE: PlcDatabase? = null

        fun getInstance(context: Context): PlcDatabase {
            val tmpInstance = INSTANCE
            if (tmpInstance != null) {
                return tmpInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext, PlcDatabase::class.java,
                    DB_NAME
                ).build()
                INSTANCE = instance
                return instance
            }
        }
    }
}